{% extends "layouts/base.html" %}

{% block title %}文档管理 - 近视预防干预系统{% endblock %}

{% block content %}
<main class="main-content-container">
  <div class="document-management-content">
    <div class="page-header">
      <h1><i class="bi bi-file-earmark-text"></i> 文档管理中心</h1>
      <p class="text-muted">管理系统文档、隐私政策、用户协议等</p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row g-3">
          <div class="col-md-8">
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-search"></i></span>
              <input type="text" class="form-control" id="searchInput" placeholder="搜索文档标题或内容...">
            </div>
          </div>
          <div class="col-md-4 text-end">
            <button id="createDocumentBtn" class="btn btn-primary">
              <i class="bi bi-file-plus"></i> 新建文档
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 文档列表 -->
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">
          <i class="bi bi-list-ul"></i> 文档列表
        </h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover" id="documentsTable">
            <thead>
              <tr>
                <th>标题</th>
                <th>类型</th>
                <th>版本</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <!-- 动态加载内容 -->
            </tbody>
          </table>
        </div>
        
        <!-- 分页器 -->
        <nav aria-label="文档分页" class="mt-3">
          <ul class="pagination justify-content-center" id="pagination">
            <!-- 动态生成分页 -->
          </ul>
        </nav>
      </div>
    </div>
  </div>
</main>

<!-- 新建/编辑文档模态框 -->
<div class="modal fade" id="documentModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="documentModalTitle">新建文档</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="documentForm">
          <input type="hidden" id="documentId" />
          <div class="mb-3">
            <label for="documentTitle" class="form-label">文档标题</label>
            <input type="text" class="form-control" id="documentTitle" required>
          </div>
          <div class="mb-3">
            <label for="documentType" class="form-label">文档类型</label>
            <select class="form-select" id="documentType" required>
              <option value="">请选择</option>
              <option value="privacy_policy">隐私政策</option>
              <option value="user_agreement">用户协议</option>
              <option value="announcement">公告通知</option>
              <option value="help_doc">帮助文档</option>
              <option value="faq">常见问题</option>
            </select>
          </div>
          <div class="mb-3">
            <label for="documentContent" class="form-label">文档内容</label>
            <textarea class="form-control" id="documentContent" rows="10" required></textarea>
          </div>
          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label for="documentVersion" class="form-label">版本号</label>
                <input type="text" class="form-control" id="documentVersion" placeholder="例: v1.0">
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label for="effectiveDate" class="form-label">生效日期</label>
                <input type="date" class="form-control" id="effectiveDate">
              </div>
            </div>
          </div>
          <div class="mb-3">
            <div class="form-check">
              <input class="form-check-input" type="checkbox" id="isMandatory">
              <label class="form-check-label" for="isMandatory">
                强制性文档（用户必须确认）
              </label>
            </div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="saveDocumentBtn">保存</button>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    loadDocuments();
    
    // 绑定事件
    document.getElementById('createDocumentBtn').addEventListener('click', showCreateDocumentModal);
    document.getElementById('saveDocumentBtn').addEventListener('click', saveDocument);
    document.getElementById('searchInput').addEventListener('input', debounce(searchDocuments, 300));
});

// 加载文档列表
function loadDocuments(page = 1) {
    AuthManager.authenticatedFetch(`/api/admin/documents?page=${page}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderDocumentsTable(data.data.documents);
                renderPagination(data.data.pagination);
            } else {
                showAlert('加载文档列表失败: ' + data.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('网络错误，请重试', 'danger');
            console.error('Error:', error);
        });
}

// 渲染文档表格
function renderDocumentsTable(documents) {
    const tbody = document.querySelector('#documentsTable tbody');
    tbody.innerHTML = '';
    
    documents.forEach(doc => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${doc.title}</td>
            <td>
                <span class="badge bg-secondary">${getDocumentTypeText(doc.document_type)}</span>
            </td>
            <td>${doc.version || 'v1.0'}</td>
            <td>
                <span class="badge bg-${getStatusColor(doc.status)}">${getStatusText(doc.status)}</span>
            </td>
            <td>${formatDate(doc.created_at)}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewDocument(${doc.id})" title="查看">
                        <i class="bi bi-eye"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="editDocument(${doc.id})" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </button>
                    ${doc.status === 'draft' ? 
                        `<button class="btn btn-outline-success" onclick="publishDocument(${doc.id})" title="发布">
                            <i class="bi bi-check-circle"></i>
                        </button>` : ''}
                    <button class="btn btn-outline-danger" onclick="deleteDocument(${doc.id})" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 工具函数
function getDocumentTypeText(type) {
    const types = {
        'privacy_policy': '隐私政策',
        'user_agreement': '用户协议',
        'announcement': '公告通知',
        'help': '帮助文档'
    };
    return types[type] || type;
}

function getStatusText(status) {
    const statuses = {
        'draft': '草稿',
        'published': '已发布',
        'archived': '已归档'
    };
    return statuses[status] || status;
}

function getStatusColor(status) {
    const colors = {
        'draft': 'secondary',
        'published': 'success',
        'archived': 'warning'
    };
    return colors[status] || 'secondary';
}

function showCreateDocumentModal() {
    document.getElementById('documentModalTitle').textContent = '新建文档';
    document.getElementById('documentForm').reset();
    document.getElementById('documentId').value = ''; // 清空documentId
    new bootstrap.Modal(document.getElementById('documentModal')).show();
}

function saveDocument() {
    // 保存文档逻辑
    const documentId = document.getElementById('documentId').value;
    const isEditing = documentId && documentId.trim() !== '';
    
    const formData = {
        title: document.getElementById('documentTitle').value,
        document_type: document.getElementById('documentType').value,
        content: document.getElementById('documentContent').value,
        version: document.getElementById('documentVersion').value,
        effective_date: document.getElementById('effectiveDate').value,
        is_mandatory: document.getElementById('isMandatory').checked
    };
    
    const url = isEditing ? `/api/admin/documents/${documentId}` : '/api/admin/documents';
    const method = isEditing ? 'PUT' : 'POST';
    
    AuthManager.authenticatedFetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert(isEditing ? '文档更新成功' : '文档创建成功', 'success');
            bootstrap.Modal.getInstance(document.getElementById('documentModal')).hide();
            loadDocuments();
        } else {
            showAlert('保存失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 查看文档详情
function viewDocument(id) {
    AuthManager.authenticatedFetch(`/api/admin/documents/${id}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const doc = data.data;
            // 显示文档详情模态框
            showDocumentDetail(doc);
        } else {
            showAlert('获取文档详情失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 编辑文档
function editDocument(id) {
    AuthManager.authenticatedFetch(`/api/admin/documents/${id}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const doc = data.data;
            // 填充编辑表单
            fillEditForm(doc);
            // 显示编辑模态框
            const modal = new bootstrap.Modal(document.getElementById('documentModal'));
            modal.show();
        } else {
            showAlert('获取文档信息失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 显示文档详情
function showDocumentDetail(doc) {
    const detailModal = document.createElement('div');
    detailModal.className = 'modal fade';
    detailModal.id = 'documentDetailModal';
    detailModal.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">文档详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>标题:</strong> ${doc.title}</p>
                            <p><strong>类型:</strong> ${getDocumentTypeText(doc.document_type)}</p>
                            <p><strong>版本:</strong> ${doc.version || 'v1.0'}</p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>状态:</strong> <span class="badge bg-${getStatusColor(doc.status)}">${getStatusText(doc.status)}</span></p>
                            <p><strong>创建时间:</strong> ${formatDate(doc.created_at)}</p>
                            <p><strong>更新时间:</strong> ${formatDate(doc.updated_at)}</p>
                        </div>
                    </div>
                    <div class="mt-3">
                        <strong>内容:</strong>
                        <div class="border p-3 mt-2" style="max-height: 300px; overflow-y: auto;">
                            ${doc.content || '暂无内容'}
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="editDocument(${doc.id}); bootstrap.Modal.getInstance(document.getElementById('documentDetailModal')).hide();">编辑</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(detailModal);
    const modal = new bootstrap.Modal(detailModal);
    modal.show();
    
    // 模态框关闭时移除DOM元素
    detailModal.addEventListener('hidden.bs.modal', function () {
        document.body.removeChild(detailModal);
    });
}

// 填充编辑表单
function fillEditForm(doc) {
    document.getElementById('documentId').value = doc.id || '';
    document.getElementById('documentTitle').value = doc.title || '';
    document.getElementById('documentType').value = doc.document_type || '';
    document.getElementById('documentContent').value = doc.content || '';
    document.getElementById('documentVersion').value = doc.version || 'v1.0';
    
    // 更新模态框标题
    document.querySelector('#documentModal .modal-title').textContent = '编辑文档';
}

// 发布文档
function publishDocument(id) {
    if (!confirm('确定要发布这个文档吗？')) {
        return;
    }
    
    AuthManager.authenticatedFetch(`/api/admin/documents/${id}/publish`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('文档发布成功', 'success');
            loadDocuments();
        } else {
            showAlert('发布失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 删除文档
function deleteDocument(id) {
    if (!confirm('确定要删除这个文档吗？此操作不可恢复！')) {
        return;
    }
    
    AuthManager.authenticatedFetch(`/api/admin/documents/${id}`, {
        method: 'DELETE'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showAlert('文档删除成功', 'success');
            loadDocuments();
        } else {
            showAlert('删除失败: ' + data.message, 'danger');
        }
    })
    .catch(error => {
        showAlert('网络错误，请重试', 'danger');
        console.error('Error:', error);
    });
}

// 搜索文档
function searchDocuments() {
    loadDocuments();
}

// 渲染分页
function renderPagination(pagination) {
    const paginationElement = document.getElementById('pagination');
    if (!paginationElement) return;
    
    let paginationHTML = '';
    
    if (pagination.has_prev) {
        paginationHTML += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadDocuments(${pagination.page - 1})">上一页</a>
        </li>`;
    }
    
    for (let i = Math.max(1, pagination.page - 2); i <= Math.min(pagination.pages, pagination.page + 2); i++) {
        const isActive = i === pagination.page ? 'active' : '';
        paginationHTML += `<li class="page-item ${isActive}">
            <a class="page-link" href="#" onclick="loadDocuments(${i})">${i}</a>
        </li>`;
    }
    
    if (pagination.has_next) {
        paginationHTML += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadDocuments(${pagination.page + 1})">下一页</a>
        </li>`;
    }
    
    paginationElement.innerHTML = paginationHTML;
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('.main-content-container').insertBefore(alertDiv, document.querySelector('.main-content-container').firstChild);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 5000);
}

// 格式化日期
function formatDate(dateString) {
    return new Date(dateString).toLocaleDateString('zh-CN');
}
</script>
{% endblock %}

